<template>
  <div class="banner-manager">
    <div class="manager-header">
      <el-button type="primary" @click="handleAdd" icon="el-icon-plus">
        新增轮播图
      </el-button>
      <el-button @click="refreshList" icon="el-icon-refresh">
        刷新
      </el-button>
    </div>

    <div class="banner-grid">
      <div
        v-for="banner in bannerList"
        :key="banner.id"
        class="banner-card"
        :class="{ 'selected': selectedBanners.includes(banner.id) }"
        @click="toggleSelect(banner)"
      >
        <div class="banner-image">
          <image-preview :src="banner.image" :width="80" :height="60"/>
          <div class="banner-overlay">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click.stop="handleEdit(banner)"
            >
              编辑
            </el-button>
          </div>
        </div>
        <div class="banner-info">
          <h4>{{ banner.title }}</h4>
          <p>{{ banner.link }}</p>
          <div class="banner-status">
            <el-tag :type="banner.status === 1 ? 'success' : 'info'">
              {{ banner.status === 1 ? '已上架' : '已下架' }}
            </el-tag>
          </div>
        </div>
        <div class="select-indicator">
          <i class="el-icon-check" v-if="selectedBanners.includes(banner.id)"></i>
        </div>
      </div>
    </div>

    <div class="manager-footer">
      <div class="selected-info">
        已选择 {{ selectedBanners.length }} 个轮播图
      </div>
      <div class="actions">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">
          确认选择
        </el-button>
      </div>
    </div>

    <!-- 轮播图编辑弹窗 -->
    <el-dialog
      :title="editMode === 'add' ? '新增轮播图' : '编辑轮播图'"
      :visible.sync="editDialogVisible"
      width="600px"
    >
      <el-form
        ref="bannerForm"
        :model="bannerForm"
        :rules="bannerRules"
        label-width="100px"
      >
        <el-form-item label="轮播图片" prop="image">
          <image-upload v-model="bannerForm.image" />
        </el-form-item>
        <el-form-item label="广告标题" prop="title">
          <el-input v-model="bannerForm.title" placeholder="请输入广告标题" />
        </el-form-item>
        <el-form-item label="跳转链接" prop="link">
          <el-input v-model="bannerForm.link" placeholder="请输入跳转链接" />
        </el-form-item>
        <el-form-item label="发布时间" prop="publishTime">
          <el-date-picker
            v-model="bannerForm.publishTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择发布时间"
          />
        </el-form-item>
        <el-form-item label="所属校区" prop="campusId" v-if="isAdmin">
          <el-select v-model="bannerForm.campusId" placeholder="请选择校区">
            <el-option
              v-for="campus in campusList"
              :key="campus.campusId"
              :label="campus.campusName"
              :value="campus.campusId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="bannerForm.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBannerAds, getBannerAds, addBannerAds, updateBannerAds } from '@/api/home/bannerAds/bannerAds'

export default {
  name: 'BannerManager',
  props: {
    selected: {
      type: Array,
      default: () => []
    },
    currentCampusId: {
      type: Number,
      default: null
    },
    isAdmin: {
      type: Boolean,
      default: false
    },
    campusList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      bannerList: [],
      selectedBanners: [],
      editDialogVisible: false,
      editMode: 'add', // add or edit
      bannerForm: {
        id: null,
        image: '',
        title: '',
        link: '',
        publishTime: '',
        status: 1,
        campusId: null
      },
      bannerRules: {
        image: [
          { required: true, message: '请上传轮播图片', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '请输入广告标题', trigger: 'blur' }
        ],
        link: [
          { required: true, message: '请输入跳转链接', trigger: 'blur' }
        ],
        publishTime: [
          { required: true, message: '请选择发布时间', trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
    this.loadBannerList()
    // 初始化已选择的轮播图
    this.initializeSelected()
  },
  watch: {
    selected: {
      handler(newVal) {
        this.initializeSelected()
      },
      immediate: true
    }
  },
  methods: {
    // 初始化已选择项
    initializeSelected() {
      if (this.selected && this.selected.length > 0) {
        // 如果传入的是轮播图对象数组，提取ID
        this.selectedBanners = this.selected.map(item =>
          typeof item === 'object' ? item.id : item
        )
      } else {
        this.selectedBanners = []
      }
    },
    // 加载轮播图列表
    async loadBannerList() {
      try {
        const query = { status: 1 } // 只显示已上架的
        
        // 如果不是超级管理员，添加校区筛选
        if (!this.isAdmin && this.currentCampusId) {
          query.campusId = this.currentCampusId
        }
        
        const response = await listBannerAds(query)
        this.bannerList = response.rows || []
      } catch (error) {
        this.$message.error('加载轮播图列表失败')
      }
    },

    // 切换选择状态
    toggleSelect(banner) {
      const index = this.selectedBanners.indexOf(banner.id)
      if (index > -1) {
        this.selectedBanners.splice(index, 1)
      } else {
        this.selectedBanners.push(banner.id)
      }
    },

    // 新增轮播图
    handleAdd() {
      this.editMode = 'add'
      this.resetForm()
      this.editDialogVisible = true
    },

    // 编辑轮播图
    handleEdit(banner) {
      this.editMode = 'edit'
      this.bannerForm = { ...banner }
      this.editDialogVisible = true
    },

    // 保存轮播图
    async handleSave() {
      this.$refs.bannerForm.validate(async (valid) => {
        if (valid) {
          try {
            if (this.editMode === 'add') {
              await addBannerAds(this.bannerForm)
              this.$message.success('新增成功')
            } else {
              await updateBannerAds(this.bannerForm)
              this.$message.success('更新成功')
            }

            this.editDialogVisible = false
            this.loadBannerList()
          } catch (error) {
            this.$message.error('保存失败')
          }
        }
      })
    },

    // 重置表单
    resetForm() {
      this.bannerForm = {
        id: null,
        image: '',
        title: '',
        link: '',
        publishTime: '',
        status: 1,
        campusId: this.isAdmin ? null : this.currentCampusId
      }
    },

    // 刷新列表
    refreshList() {
      this.loadBannerList()
    },

    // 取消选择
    handleCancel() {
      this.$emit('close')
    },

    // 确认选择
    handleConfirm() {
      const selectedBannerData = this.bannerList.filter(banner =>
        this.selectedBanners.includes(banner.id)
      )
      this.$emit('select', selectedBannerData)
    }
  }
}
</script>

<style scoped>
.banner-manager {
  height: 500px;
  display: flex;
  flex-direction: column;
}

.manager-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.banner-grid {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
  overflow-y: auto;
  padding: 10px 0;
}

.banner-card {
  position: relative;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s;
}

.banner-card:hover {
  border-color: #1976d2;
  box-shadow: 0 4px 12px rgba(25, 118, 210, 0.15);
}

.banner-card.selected {
  border-color: #1976d2;
  background-color: #e3f2fd;
}

.banner-image {
  position: relative;
  height: 120px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.banner-image >>> .el-image {
  width: 100%;
  height: 100%;
}

.banner-image >>> .el-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.banner-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.banner-card:hover .banner-overlay {
  opacity: 1;
}

.banner-info {
  padding: 15px;
}

.banner-info h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.banner-info p {
  margin: 0 0 10px 0;
  font-size: 12px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.banner-status {
  display: flex;
  justify-content: flex-end;
}

.select-indicator {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: #1976d2;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.banner-card.selected .select-indicator {
  opacity: 1;
}

.manager-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #e0e0e0;
}

.selected-info {
  color: #666;
  font-size: 14px;
}

.actions {
  display: flex;
  gap: 10px;
}
</style>
